﻿jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
};

jQuery.fn.tooltip = function (title) {
	if (!title) {
		if (!$(this).attr('title')) return this;
		title = $(this).attr('title').replace(/\n/g, "<br />");
	} else title = title.replace(/\n/g, "<br />");
    $(this).removeAttr('title').unbind('mouseover').unbind('mousemove').unbind('mouseout')
	.mouseover(function () {
	    $('#tooltip').html('<p>' + title + '</p>').css({ opacity: 0.8, display: "none", zIndex: 9999 }).fadeIn(10);
	}).mousemove(function (kmouse) {
	    $('#tooltip').css({ left: kmouse.pageX + 15, top: kmouse.pageY + 15 });
	}).mouseout(function () {
	    $('#tooltip').fadeOut(10);
	});
	return this;
};

(function( $ ) {
	$.widget( "ui.combobox", {
		options: {
			strict: true,
			change: null
		},
		_create: function() {
			var self = this,
				select = this.element.hide(),
				selected = select.children( ":selected" ),
				value = selected.val() ? selected.text() : "";
			var input = this.input = $( "<input>" )
				.insertAfter( select )
				.val( value )
				.autocomplete({
					delay: 0,
					minLength: 0,
					source: function( request, response ) {
						var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
						response( select.children( "option" ).map(function() {
							var text = $( this ).text();
							if ( this.value && ( !request.term || matcher.test(text) ) )
								return {
									label: text.replace(
										new RegExp(
											"(?![^&;]+;)(?!<[^<>]*)(" +
											$.ui.autocomplete.escapeRegex(request.term) +
											")(?![^<>]*>)(?![^&;]+;)", "gi"
										), "<strong>$1</strong>" ),
									value: text,
									option: this
								};
						}) );
					},
					select: function( event, ui ) {
						ui.item.option.selected = true;
						if (self.options.change) self.options.change($(ui.item.option).val(), $(ui.item.option).text());
						self._trigger( "selected", event, {
							item: ui.item.option
						});
					},
					change: function( event, ui ) {
						if ( !ui.item ) {
							var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
								valid = false;
								select.children( "option" ).each(function() {
								if ( $( this ).text().match( matcher ) ) {
									this.selected = valid = true;
									if (self.options.change) self.options.change($(this).val(), $(this).text());
									return false;
								}
							});
							if ( !valid ) {
								if (self.options.strict == true) {
									// remove invalid value, as it didn't match anything
									$( this ).val( "" );
									select.val( "" );
									input.data( "autocomplete" ).term = "";
								}
								return false;
							}
						}
					}
				})
				.addClass( "ui-widget ui-widget-content ui-corner-left" );

			input.data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>" + item.label + "</a>" )
					.appendTo( ul );
			};

			this.button = $( "<button type='button'>&nbsp;</button>" )
				.attr( "tabIndex", -1 )
				.attr( "title", "Show All Items" )
				.insertAfter( input )
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				})
				.removeClass( "ui-corner-all" )
				.addClass( "ui-corner-right ui-button-icon" )
				.click(function() {
					// close if already visible
					if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
						input.autocomplete( "close" );
						return;
					}

					// work around a bug (likely same cause as #5265)
					$( this ).blur();

					// pass empty string as value to search for, displaying all results
					input.autocomplete( "search", "" );
					input.focus();
				}).css({'width': '27px', 'height': '27px', position: 'relative', top: '6px', left: '-2px'});
		},

		destroy: function() {
			this.input.remove();
			this.button.remove();
			this.element.show();
			$.Widget.prototype.destroy.call( this );
		}
	});
})( jQuery );

// ******************* Confirm dialog *********************
var Confirm = function(question, yes_callback, no_callback) {
	$('#ask_yes_no').attr('title', question).dialog({ title: question, buttons: {
		'Yes': function () {
			yes_callback();
			$('#ask_yes_no').dialog('close');
		},
		'Cancel': function () {
			if (no_callback) no_callback();
			$('#ask_yes_no').dialog('close');
		}
	}
	});
};

function Warning(title, text) {
	console.log(title);
	console.log(text);
}

$(function () {
    $("#tabs").tabs();
    //$("#tabs").height($(document).height() - 100);
    //$("#infopanel").height($("#tabs").height() - 80);
    $("#menupanel").offset({ left: $("#infopanel").width() + 50, top: $("#infopanel").position().top + 10 });
	$('#sheets').tabs();
	$('#reports').tabs();
	$('#settings').tabs();
	$("input[type=file]").filestyle({ 
		image: "/img/file.png",
		imageheight : 38,
		imagewidth : 139,
		width : 250
	});
	$('.file').addClass('ui-widget ui-widget-content ui-corner-all').css({'margin-top': '10px', 'margin-bottom': '5px'});
	var dcfull = new DcFull();
	var rackfull = new RackFull();
	var serverfull = new ServerFull();
	var iplist = new IpList();
	//$('#tab-servers table').width($('#tab-servers').width() - 150);

    var dc_info = new Dc();
	
	$('.sheets_dc_reload').button().click(function() {
		dcfull.Load();
		return false;
	});
	
	$('.sheets_dc_add').button().click(function() {
		dcfull.Add();
		return false;
	});
	
	$('.sheets_rack_reload').button().click(function() {
		rackfull.Load();
		return false;
	});
	
	$('.sheets_rack_add').button().click(function() {
		rackfull.Add();
		return false;
	});
	
	$('.sheets_server_reload').button().click(function() {
		serverfull.Load();
		return false;
	});
	
	$('.sheets_server_add').button().click(function() {
		serverfull.Add();
		return false;
	});
	
	$('.report_ips_reload').button().click(function() {
		iplist.Load();
		return false;
	});
	//<a href="#" class="sheets_dc_export">Export</a>
	$('.sheets_dc_export').button().click(function() {
		window.open('/call.aspx?source=export&table=dc');
	});
	$('.sheets_rack_export').button().click(function() {
		window.open('/call.aspx?source=export&table=rack');
	});
	$('.sheets_server_export').button().click(function() {
		window.open('/call.aspx?source=export&table=server');
	});
	$('.report_ips_export').button().click(function() {
		window.open('/call.aspx?source=export&table=ip');
	});
	
	$('#import-form').submit(function() { 
		// submit the form 
		$(this).ajaxSubmit(function(data) {
			console.log(data);
			$('#info').dialog('destroy').empty().append(data).dialog({minWidth: 600});
		}); 
		// return false to prevent normal browser submit and page navigation 
		return false; 
	});
	$('#form_server_color').jPicker({position: {x: 'center', y: 'center'}});
	$('#err').ajaxError(function(e, jqxhr, settings, exception) {
		if (exception.indexOf('SyntaxError: Unexpected token') > -1) exception = 'System Error';
		$(this).html('Error: ' + exception + "<br />");
		$('<a href="#" class="err_details">Details</a>').appendTo($(this)).button().click(function() {
			$('#info').html(jqxhr.responseText).dialog({minWidth:600});
		});
	});
});

/*

add a button to dialog
$("<a href='#' style='float:right; margin-right:1em;'></a>").button({icons:{primary: "ui-icon-plus"},text: false}).insertBefore('.ui-dialog-titlebar-close').click(function(e){
   e.preventDefault();
   alert("click");
});
*/
